#!/usr/bin/env python

"""CLI based on argparse module"""

from __init__ import __version__, __maintainer__, __email__
from htools import flatten_dir_list
import sys
import argparse


class CLI(object):
    """
    Command-Line-Interface setup

    Based on argparse - see also:
    http://docs.python.org/library/argparse.html
    http://www.doughellmann.com/PyMOTW/argparse/
    """
    def __init__(self, description='', usage='', epilog='', add_help=False):
        """
        Setup parser obj - see also
        http://docs.python.org/library/argparse.html#argumentparser-objects
        """
        self.parser = argparse.ArgumentParser(description=description,
                                              usage=usage,
                                              epilog=epilog,
                                              add_help=add_help)
        self.gr = {}
        self.add_group('pos', 'Positional arguments')
        self.add_group('pro', 'Processing control')
        self.add_group('log', 'Logging control'),
        self.add_group('inf', 'Program information')

    def add_group(self, gid, name):
        """Add an argument group for nicer formatting. Access by gid."""
        self.gr[gid] = self.parser.add_argument_group(name)

    def parse(self, cmd_args=None):
        """Run argument parser"""
        if cmd_args is not None:
            args = self.parser.parse_args(cmd_args)
        else:
            args = self.parser.parse_args()
        return args

def get_cli_args(cmd_args=None):
    """Build custom CLI"""
    usage = "%(prog)s [options] infile outfile"
    description = "Generic template for Python command line script with options."
    epilog = "For help contact %s <%s>" % (__maintainer__, __email__)

    cli = CLI(description=description, usage=usage, epilog=epilog)

    # Positional arguments
    cli.gr['pos'].add_argument('inlist', nargs='+', type=str, help='Input dir or files')
    #cli.gr['pos'].add_argument('outfile', nargs='?', type=argparse.FileType('w'),
    #                    default=sys.stdout, help='Output file (default: STDOUT)')

    # Processing control
    # cli.gr['pro'].add_argument('--dir', nargs='+', type=str,
    #                 action='append', dest='dir',
    #                 help='Top-level directory to scan recursively for image files; shell wildcards are accepted')

    # Create debug LEVEL arguments
    cli.gr['log'].add_argument('--log', type=argparse.FileType('a'),   # Will open a file for writing.
                    default = sys.stderr, metavar='file', dest='log_output', help='Log file (default: STDERR)')
    cli.gr['log'].add_argument('-l', '--log-level', metavar='LEVEL', dest='log_level',
                    default='INFO', choices='DEBUG INFO WARN ERROR CRITICAL'.split(),
                    help="Choose a log level from DEBUG, INFO (default), WARN, ERROR or CRITICAL")
    cli.gr['log'].add_argument('-q', '--quiet',
                    action='store_const', dest='log_level', const='ERROR',
                    help="Alias for --log-level ERROR")
    cli.gr['log'].add_argument('-v', '--verbose',
                    action='store_const', dest='log_level', const='DEBUG',
                    help="Alias for --log-level DEBUG")

    # Create Program Information
    cli.gr['inf'].add_argument('-V', '--version', action='version',
                    version=__version__, help='Show version number and exit')
    cli.gr['inf'].add_argument('-h', '--help', action='help',
                    help='Show this help message and exit')

    # Run parser
    args = cli.parse(cmd_args)

    # Cleanup directory list
    # args.dir = flatten_dir_list(args.dir)

    return args
